package im.yangqiang.android.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import im.yangqiang.android.ui.R;


/**
 * 切换的ViewPager标题的指示器。有两种形态，一种是文字下面是一根线，一种是滑块在文字上面。
 * Create by Carlton on 2014/07/03
 */
public class ViewPagerTabStrip extends HorizontalScrollView implements ViewPager.OnPageChangeListener
{
    /**
     * 块状
     */
    public static final int BLOCK = 1;
    /**
     * 线
     */
    public static final int LINE = 2;
    /**
     * 指示器和控件的水平间距
     */
    private final int INDICATOR_HORIZONTAL_SPACE = 10;
    /**
     * 指示器和控件的垂直间距
     */
    private final int INDICATOR_VERTICAL_SPACE = 10;
    private ViewPager.OnPageChangeListener mOnPageChangeListener;
    private ViewPager mPager;
    private LinearLayout mRootLayout;
    private int mScrollIndex = 0;
    private int mLinePaddingLeft;
    private int mLinePaddingRight;

    public ViewPagerTabStrip(Context context)
    {
        super(context);
        init(context, null, 0);
    }

    public ViewPagerTabStrip(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ViewPagerTabStrip(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private int mTextAppearance = -1;
    private int mTextSize = -1;
    private int mTextColor = -1;
    private int mTextPadding = -1;
    private int mTextPaddingLeft = -1;
    private int mTextPaddingTop = -1;
    private int mTextPaddingRight = -1;
    private int mTextPaddingBottom = -1;
    private int mSlideColor = Color.BLUE;
    private float mSlideWidth = 0;
    /**
     * 是否绘制Tab下面的横线
     */
    private boolean isTabLine = true;
    /**
     * 是否显示滑块
     */
    private boolean isSlidBlock = false;

    public boolean isTabLine()
    {
        return isTabLine;
    }

    public void setTabLine(boolean isTabLine)
    {
        this.isTabLine = isTabLine;
    }

    public boolean isSlidBlock()
    {
        return isSlidBlock;
    }

    public void setSlidBlock(boolean isSlidBlock)
    {
        this.isSlidBlock = isSlidBlock;
    }

    public int getIndicatorType()
    {
        return isTabLine ? LINE : BLOCK;
    }

    /**
     * 初始化
     *  @param context
     * @param attrs
     * @param defStyle
     */
    private void init(Context context, AttributeSet attrs, int defStyle)
    {
        setFillViewport(true);
        setHorizontalScrollBarEnabled(false);
        mRootLayout = new LinearLayout(getContext());
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        mRootLayout.setGravity(Gravity.CENTER);
        mRootLayout.setLayoutParams(params);
        mRootLayout.setOrientation(LinearLayout.HORIZONTAL);
        mRootLayout.setPadding(getPaddingLeft(), 0, getPaddingRight(), 0);
        addView(mRootLayout);

        final TypedArray appearance = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerTabStrip,defStyle, 0);
        mSlideWidth = appearance.getDimensionPixelOffset(R.styleable.ViewPagerTabStrip_slideWidth, 6);
        mTextAppearance = appearance.getResourceId(R.styleable.ViewPagerTabStrip_textAppearance, -1);
        mTextSize = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_android_textSize, 12);
        mTextColor = appearance.getColor(R.styleable.ViewPagerTabStrip_android_textColor, Color.BLACK);
        mTextPadding = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_textPadding, 0);
        mTextPaddingLeft = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_textPaddingLeft, 0);
        mTextPaddingTop = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_textPaddingTop, 0);
        mTextPaddingRight = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_textPaddingRight, 0);
        mTextPaddingBottom = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_textPaddingBottom, 0);
        mSlideColor = appearance.getColor(R.styleable.ViewPagerTabStrip_slideColor, Color.BLUE);
        isTabLine = appearance.getInt(R.styleable.ViewPagerTabStrip_type, LINE) == LINE;
        isSlidBlock = !isTabLine;
        mLinePaddingLeft = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_linePaddingLeft, 0);
        mLinePaddingRight = appearance.getDimensionPixelSize(R.styleable.ViewPagerTabStrip_linePaddingRight, 0);
        appearance.recycle();
        if (isInEditMode())
        {
            addDemoData();
        }
    }

    /**
     * 添加演示数据
     */
    private void addDemoData()
    {
        final CharSequence[] titles = new CharSequence[3];
        for (int i = 0; i < titles.length; ++i)
        {
            titles[i] = "Text" + (i + 1);
        }
        addChildView(titles);
    }

    public void setViewPager(ViewPager viewPager)
    {
        mPager = viewPager;
        mPager.addOnPageChangeListener(this);
        if (mPager == null || mPager.getAdapter() == null)
        {
            return;
        }
        final PagerAdapter adapter = mPager.getAdapter();
        final int count = adapter.getCount();
        final CharSequence[] titles = new CharSequence[count];
        for (int i = 0; i < count; ++i)
        {
            titles[i] = adapter.getPageTitle(i);
        }
        addChildView(titles);
    }

    /**
     * 是否可用
     *
     * @param obj
     * @return
     */
    private boolean isUse(int obj)
    {
        return obj != -1;
    }

    /**
     * Tab点击事件
     */
    private OnTabClickListener mOnTabClickListener;

    /**
     * 设置事件
     *
     * @param listener
     */
    public void setOnTabClickListener(OnTabClickListener listener)
    {
        mOnTabClickListener = listener;
    }

    /**
     * 添加孩子视图
     */
    private void addChildView(CharSequence[] titles)
    {
        if (titles == null)
        {
            return;
        }
        mRootLayout.removeAllViews();
        for (int i = 0; i < titles.length; ++i)
        {
            final TextView child = new TextView(getContext());
            child.setText(titles[i]);
            child.setTag(i);
            setTextViewAppearance(child);
            //            if (i == 0)
            //            {
            //                setFirstPadding(child);
            //            }
            //            if (i == titles.length - 1)
            //            {
            //                setLastPadding(child);
            //            }
            child.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Integer index = (Integer) v.getTag();
                    mPager.setCurrentItem(index);
                    if (mOnTabClickListener != null)
                    {
                        mOnTabClickListener.onTabClick(child, index);
                    }
                }
            });
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.weight = 1;
            child.setGravity(Gravity.CENTER);
            mRootLayout.addView(child, params);
        }
        if (mRootLayout.getChildCount() > 0)
        {
            mRootLayout.getChildAt(0).setSelected(true);
        }
        invalidate();
    }

    protected void setFirstPadding(TextView view)
    {
        view.setPadding(view.getPaddingLeft() * 2, view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
    }

    protected void setLastPadding(TextView view)
    {
        view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight() * 2, view.getPaddingBottom());
    }

    /**
     * 设置TextView属性
     *
     * @param textView
     */
    private void setTextViewAppearance(TextView textView)
    {
        if (isUse(mTextAppearance))
        {
            textView.setTextSize(mTextSize);
        }
        if (isUse(mTextColor))
        {
            textView.setTextColor(mTextColor);
        }
        if (isUse(mTextAppearance))
        {
            textView.setTextAppearance(getContext(), mTextAppearance);
        }
        if (isUse(mTextPadding))
        {
            textView.setPadding(mTextPadding, mTextPadding, mTextPadding, mTextPadding);
        }
        if (isUse(mTextPaddingLeft))
        {
            textView.setPadding(mTextPaddingLeft, textView.getPaddingTop(), textView.getPaddingRight(), textView.getPaddingBottom());
        }
        if (isUse(mTextPaddingTop))
        {
            textView.setPadding(textView.getPaddingLeft(), mTextPaddingTop, textView.getPaddingRight(), textView.getPaddingBottom());
        }
        if (isUse(mTextPaddingRight))
        {
            textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), mTextPaddingRight, textView.getPaddingBottom());
        }
        if (isUse(mTextPaddingBottom))
        {
            textView.setPadding(textView.getPaddingLeft(), textView.getPaddingTop(), textView.getPaddingRight(), mTextPaddingBottom);
        }
        textView.setFocusable(true);
        textView.setSingleLine();
    }

    private RectF mOutRect = new RectF();
    private Paint mPaint = new Paint();
    private Rect mContentRect = new Rect();

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        if (mRootLayout == null)
        {
            return;
        }
        View childView = mRootLayout.getChildAt(mScrollIndex);
        if (childView == null)
        {
            return;
        }
        final int paddingLeft = getPaddingLeft();
        final int paddingTop = getPaddingTop();
        final int paddingRight = getPaddingRight();
        final int paddingBottom = getPaddingBottom();

        final int childAtLeft = childView.getLeft();
        final int childAtRight = childView.getRight();
        final int childPaddingLeft = childView.getPaddingLeft();
        final int childPaddingRight = childView.getPaddingRight();
        final int childPaddingBottom = childView.getPaddingBottom();
        final int childPaddingTop = childView.getPaddingTop();


        final int widthPixels = getResources().getDisplayMetrics().widthPixels;
        int heightPixels = mRootLayout.getHeight();
        mContentRect.set(paddingLeft + getScrollX(), paddingTop, widthPixels - paddingRight + getScrollX(), heightPixels + paddingTop);

        // 绘制内容区域
        // mPaint.setColor(Color.RED);
        // canvas.drawRect(mContentRect, mPaint);


        mOutRect.left = getLimitLeft(childAtLeft + childPaddingLeft + paddingLeft + mDynPositionLeft);
        // 动态绘制滑块的右边位置
        mOutRect.right = getLimitRight(childAtRight - childPaddingRight + paddingLeft + mDynPositionLeft + mOffsetDistance);

        if (isTabLine)
        {
            mOutRect.top = mRootLayout.getBottom() - mSlideWidth + paddingTop;
            mOutRect.bottom = mRootLayout.getBottom();
            mOutRect.left -= (childPaddingLeft - mLinePaddingLeft);
            mOutRect.right += (childPaddingRight - mLinePaddingRight);
            mPaint.setColor(mSlideColor);
            canvas.drawRect(mOutRect, mPaint);
        }
        if (isSlidBlock)
        {
            mPaint.setColor(mSlideColor);
            mOutRect.left = getLimitLeft(mOutRect.left - INDICATOR_HORIZONTAL_SPACE);
            mOutRect.right = getLimitRight(mOutRect.right + INDICATOR_HORIZONTAL_SPACE);
            mOutRect.top = mContentRect.top + childPaddingTop;
            mOutRect.bottom = mContentRect.bottom - childPaddingBottom;
            canvas.drawRoundRect(mOutRect, 10.0f, 10.0f, mPaint);
        }
    }

    /**
     * 获取被限制的左边位置（左边永远不会超过边距)
     *
     * @param left
     * @return
     */
    private int getLimitLeft(float left)
    {
        return (int) Math.max(mContentRect.left, left);
    }

    private int getLimitRight(float right)
    {
        return (int) Math.min(mContentRect.right, right);
    }

    /**
     * 背景或者横线移动的时候动态的位置, 动态设置滑块的位置可以在滑动的时候让滑块保持位置不变
     */
    private int mDynPositionLeft = 0;
    /**
     * 背景或者下横线相对于开始状态和结束状态，其中偏移的距离
     */
    private float mOffsetDistance = 0;

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
    {
        mScrollIndex = position;
        final View pageIndexView = mRootLayout.getChildAt(position);

        if (pageIndexView != null)
        {
            // 背景或者下面横线移动的动态位置
            int dynPosition = (int) (positionOffset * pageIndexView.getWidth());
            smoothScrollTo(dynPosition + pageIndexView.getLeft() - 50, 0);
            mDynPositionLeft = dynPosition;

            // 下一个控件的宽减去当前控件的宽，然后使用偏移量去计算当前偏移量下面应该的距离
            int nextIndex = (mRootLayout.getChildCount() > position + 1) ? position + 1 : position;
            final View nextChild = mRootLayout.getChildAt(nextIndex);
            mOffsetDistance = (nextChild.getWidth() - pageIndexView.getWidth()) * positionOffset;

            invalidate();
        }
        if (mOnPageChangeListener != null)
        {
            mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    }

    @Override
    public void onPageSelected(int position)
    {
        final View currView = mRootLayout.getChildAt(position);
        resetSelectState();
        currView.setSelected(true);
        if (mOnPageChangeListener != null)
        {
            mOnPageChangeListener.onPageSelected(position);
        }
    }

    /**
     * 重置状态
     */
    protected void resetSelectState()
    {
        for (int i = 0; i < mRootLayout.getChildCount(); ++i)
        {
            View view = mRootLayout.getChildAt(i);
            view.setSelected(false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state)
    {
        if (mOnPageChangeListener != null)
        {
            mOnPageChangeListener.onPageScrollStateChanged(state);
        }
    }

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener)
    {
        mOnPageChangeListener = onPageChangeListener;
    }

    /**
     * Tab点击事件
     */
    public static interface OnTabClickListener
    {
        public void onTabClick(View view, int position);
    }
}
